<template>
  <div class="trainOrder">
    <div class="header"></div>
    <div class="body">
      <div class="form">
        <el-form
          :label-position="labelPosition"
          :model="formLabelAlign"
          :inline="true"
        >
          <el-form-item label="订单号">
            <el-input
              size="mini"
              v-model="formLabelAlign.orderId"
            ></el-input>
          </el-form-item>
          <el-form-item label="乘客姓名" class="el-form-item">
            <el-input size="mini" v-model="formLabelAlign.passengerName"></el-input>
          </el-form-item>
          <el-form-item label="联系人手机号">
            <el-input size="mini" v-model="formLabelAlign.passengerPhone"></el-input>
          </el-form-item>
          <el-form-item label="车次">
            <el-input
              size="mini"
              v-model="formLabelAlign.trainNumber"
            ></el-input>
          </el-form-item>
          <el-form-item label="会员卡号">
            <el-input
              size="mini"
              v-model="formLabelAlign.cardNumber"
            ></el-input>
          </el-form-item>
          <el-form-item label="合作商订单号">
            <el-input
              size="mini"
              v-model="formLabelAlign.tripartiteOrderId"
            ></el-input>
          </el-form-item>
          <el-form-item label="订单来源">
            <el-select v-model="formLabelAlign.orderSource" clearable size="mini">
              <el-option label="CRM" value="crm"></el-option>
              <el-option label="小程序" value="program"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="预定时间">
            <el-date-picker
              :value-format="format"
              size="mini"
              style="width: 150px"
              v-model="formLabelAlign.createTime"
              type="date"
            >
            </el-date-picker>
            <span style="color: #525558">至</span>
            <el-date-picker
              :value-format="format"
              size="mini"
              style="width: 150px"
              v-model="formLabelAlign.endCreateTime"
              type="date"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select
              size="mini"
              v-model="formLabelAlign.status"
              placeholder="请选择订单状态"
              clearable
            >
              <el-option
                v-for="item in orderstatusList"
                :key="item.id"
                :label="item.names"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="btn">
      <el-button
        style="background-color: rgb(246, 178, 62); color: #fff"
        @click="search"
        >查询订单</el-button
      >
      <!-- <el-button type="success">导出Excel</el-button> -->
    </div>
    <div class="table">
      <el-table
        size="mini"
        :header-cell-style="{
          color: '#fff',
          background: '#6090EC',
          fontSize: '11px',
          fontWeight: 'normal',
        }"
        :data="dataList"
        border
      >
        <el-table-column prop="orderId" label="订单号" width="150"> </el-table-column>
        <!-- <el-table-column prop="tripartiteOrderId" label="合作单号">
        </el-table-column> -->
        <el-table-column prop="trainNumber" label="车次号"> </el-table-column>
        <el-table-column prop="passengerName" label="乘客姓名" width="90px">
        </el-table-column>
        <el-table-column min-width="60px" prop="ticketTotalAmount" label="票面价">
        </el-table-column>
        <el-table-column min-width="50px" prop="actualPayAmount" label="总价 ">
          <template slot-scope="scope">
            {{scope.row.ticketTotalAmount+scope.row.serviceCharge}}
          </template>
        </el-table-column>
        <el-table-column width="100px" prop="departureDate" label="乘车日期">
        </el-table-column>
        <el-table-column width="140px" prop="createTime" label="预定时间">
        </el-table-column>
        <el-table-column width="80px" prop="departureTime" label="发车">
        </el-table-column>
        <el-table-column width="100px" prop="zuoweihao" label="座位号">
        </el-table-column>
        <el-table-column min-width="80px" prop="departureStation" label="出发车站">
        </el-table-column>
        <el-table-column min-width="80px" prop="arrivalStation" label="到达车站">
        </el-table-column>
        <el-table-column min-width="130px" label="订单状态">
          <template slot-scope="scope"> 
            {{scope.row.orderStatus | orderStatus}}
          </template>
        </el-table-column>
        <el-table-column min-width="130px" label="订单来源">
          <template slot-scope="scope"> 
            {{scope.row.orderSource | orderSource}}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200px" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.btnGroupStatus.detaileBtn"
              size="mini"
              type="primary"
              @click="detailsList(scope.$index, scope.row)"
            >详情</el-button>
            <el-button
              v-if="scope.row.btnGroupStatus.goPayBtn"
              size="mini"
              type="primary"
              @click="topayfor(scope.$index, scope.row)"
            >去支付</el-button>
            <el-button
              v-if="scope.row.btnGroupStatus.goPayChangeBtn"
              size="mini"
              type="primary"
              @click="topayfor(scope.$index, scope.row,'change')"
            >去支付</el-button>
            <el-button
              v-if="scope.row.btnGroupStatus.cancelBtn"
              size="mini"
              type="primary"
              @click="cancelorder(scope.$index, scope.row)"
            >取消订单</el-button>
            <el-button
              v-if="scope.row.btnGroupStatus.cancleChangeBtn"
              size="mini"
              type="primary"
              @click="cancelorder(scope.$index, scope.row,'change')"
            >取消改签</el-button>
            <!--   -->
            <el-button
              v-if="scope.row.btnGroupStatus.changeBtn"
              size="mini"
              type="primary"
              @click="handleChange(scope.$index, scope.row), (changeOrder = true)"
              >改签</el-button
            >
            <!-- <el-button
              size="mini"
              @click="trainModify(scope.row)"
              type="primary"
              >修改</el-button> -->
            <el-button
              v-if="scope.row.btnGroupStatus.returnBtn"
              size="mini"
              type="primary"
              @click="handleDetails(scope.$index, scope.row)"
              >退票</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 取消订单 -->
    <el-dialog title="提示" :visible.sync="cancelorderVisible" width="30%">
      <span>请确认是否取消订单</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelorderVisible = false">取 消</el-button>
        <el-button type="primary" @click="getcancelOrder">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <div class="total">
      <p>共{{this.total}}条</p>
    </div> -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageTotal"
    >
    </el-pagination>
    <!-- 退票 -->
    <el-dialog
      title="退票"
      :visible.sync="cancellog"
      :close-on-click-modal="false"
      width="60%"
    >
      <el-table
        size="mini"
        ref="multipleReturnTable"
        :data="trainOrderItemList"
        tooltip-effect="dark"
        :header-cell-class-name="cellClass"
        @select="handleSelectionChange"
      >
        <el-table-column type="selection" width="45" :selectable="returnOrderDisabled" > </el-table-column>
        <el-table-column prop="passengerName" label="乘客姓名" width="100">
        </el-table-column>
        <el-table-column prop="idNumber" label="证件号" width="160"> </el-table-column>
        <el-table-column prop="ticketNumber" label="票号" width="160">
        </el-table-column>
        <el-table-column prop="trainBox" label="车厢号" width="80">
        </el-table-column>
        <el-table-column prop="seatNo" label="座位号" width="80">
        </el-table-column>
        <el-table-column width="130px" label="订单状态">
          <template slot-scope="scope"> 
            {{scope.row.orderItemStatus | orderStatus}}
          </template>
        </el-table-column>
      </el-table>
      <!-- 退款方式 -->
      <el-radio-group v-model="refundway">
        <el-radio label="线上品牌商赞助">原路返回</el-radio>
        <el-radio label="线下场地免费">退至预留款</el-radio>
      </el-radio-group>
      <el-button
        style="background-color: #6090ec; color: #fff; margin: 10px 10px 0 36%"
        @click="getretreatTicket"
        >确认退票
      </el-button>
      <el-button
        style="background-color: #6090ec; color: #fff"
        @click="cancellog = false"
        >取消</el-button
      >
    </el-dialog>
    <!-- 改签 -->
    <el-dialog
      title="选择改期乘客"
      :visible.sync="changeOrder"
      :close-on-click-modal="false"
    >
      <el-table
        :data="tableData"
        size="mini"
        ref="multipleChangeTable"
        :header-cell-class-name="cellClass"
        @select="handleselectChange"
      >
        <el-table-column type="selection" width="55" :selectable="changeOrderDisabled"></el-table-column>
        <el-table-column
          property="orderId"
          label="主键编号"
          width="150"
        ></el-table-column>
        <el-table-column
          property="passengerName"
          label="姓名"
          width="100"
        ></el-table-column>
        <el-table-column property="idType" 
          min-width="120" label="证件类型">
          <template slot-scope="scope">
            <template v-if="scope.row.idType == 'ZGJMSFZ'">中国居民身份证</template>
            <template v-if="scope.row.idType == 'GATJMJZZ'">港澳台居民居住证</template>
            <template v-if="scope.row.idType == 'GAJMLWNDTXZ'">港澳居民来往内地通行证</template>
            <template v-if="scope.row.idType == 'TWJMLWDLTXZ'"
              >台湾居民来往大陆通行证</template
            >
            <template v-if="scope.row.idType == 'HZ'"
              >护照</template
            >
            <template v-if="scope.row.idType == 'WGRYJJLSFZ'"
              >外国人永久居留身份证</template
            >
          </template>
        </el-table-column>
        <el-table-column
          property="idNumber"
          label="证件号"
          width="180"
        ></el-table-column>
        <el-table-column
          property="trainBox"
          label="车厢"
          width="130"
        ></el-table-column>
        <el-table-column
          property="ticketNumber"
          label="票号"
          width="150"
        ></el-table-column>
        <el-table-column width="130px" label="订单状态">
          <template slot-scope="scope">
             {{scope.row.orderItemStatus | orderStatus}}
          </template>
        </el-table-column>
        <!-- <el-table-column property="orderStatus" label="订单状态"></el-table-column> -->
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changeOrder = false">取 消</el-button>
        <el-button type="primary" @click="btnChange">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog
      title="修改乘车人信息"
      :visible.sync="trainModifywindow"
      width="60%"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" size="mini">
        <div style="display: flex">
          <el-form-item label="姓名" prop="name" style="display: flex">
            <el-input style="width: 120px" v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="name" style="display: flex">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="身份证号" prop="name" style="display: flex">
            <el-input style="width: 200px" v-model="ruleForm.name"></el-input>
          </el-form-item>
        </div>
        <el-form-item style="margin: 30px 0 0 45%">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >保存</el-button
          >
          <el-button @click="trainModifywindow = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>


<script>
export default {
  name: "trainOrder",
  data() {
    return {
      // 退款方式
      refundway: "",
      arrlist: [],
      ruleForm: {
        name: "",
      },
      merchantOrderIdNowArr:[],
      rules: {
        name: [
          {
            required: true,
            message: "请输入活动名称",
            trigger: "blur",
          },
        ],
      },
      trainModifywindow: false,
      customerId: "",
      train: "",
      format: "yyyy-MM-dd",
      trainCancel: {},
      trainSelIndex :null,
      cancelorderVisible: false,
      dialogType:"",
      passenger: "",
      orderItemID: [],
      train: {},
      // 乘客数组
      trainOrderItemList: [],
      //分页
      pageSize: 10,
      currentPage: 1,
      pageTotal: 0,
      cancellog: false,
      size: "",
      changeOrder: false,
      orderstatusList: [
        {
          id: "unpaid",
          names: "未支付",
        },
        {
          id: "seatFail",
          names: "占座失败",
        },
        {
          id: "payFail",
          names: "支付失败",
        },
        {
          id: "haspay",
          names: "支付成功",
        },
        {
          id: "cancelpay",
          names: "取消订单",
        },
        {
          id: "outTicketSuccess",
          names: "出票成功",
        },
        {
          id: "refundTicketSuccess",
          names: "退票成功",
        },
        {
          id: "changeTicket",
          names: "改签中",
        },
        {
          id: "changeTicketSuccess",
          names: "改签成功",
        },
        {
          id: "changeTicketFail",
          names: "改签失败",
        },
        {
          id: "changeRefundTicketSuccess",
          names: "改签退票成功",
        },
      ],
      // 返回数据
      dataList: [],
      go: "",
      lists: "",
      trainOrderItem: [],
      dataollection: [],
      labelPosition: "right",
      formLabelAlign: {
        cardNumber: "",
        customerName: "",
        passengerName: "",
        orderId: "",
        passengerPhone: "",
        trainNumber: "",
        status: "",
        tripartiteOrderId: "",
        ticketNumber: "",
        orderSource: "",
        orderType: "",
        movement: "",
        orderstatus: "",
        source: "",
        channels: "",
        createTime: "",
        endCreateTime: "",
      },
      changeMes: {},
      // 下拉框
      form: {
        region: "",
        ticketChannel: "",
      },
      // 表格
      tableData: [],
      changeTable: [],
      orderid: "",
      jsjid: "",
    };
  },
  props: {},
  components: {},
  methods: {
    cellClass(row){
      if (row.columnIndex === 0 && row.rowIndex === 0) {
        return 'disableheadselection'
      }
    },

    // 修改确定按钮
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 修改按钮
    trainModify(row) {
      console.log(row);
      this.trainModifywindow = true;
    },
    // 详情
    detailsList(index,row ) {
      console.log(row, index);
      this.fsadaf = row;
      console.log(this.fsadaf); // this.$router.replace("/customer/refundCard");
      this.$router.push({
        name: "trainOrderDetails",
        params: {
          fsadaf: this.fsadaf, // jsjid:row.jsjid
        },
      });
    },

    topayfor(index, row,type = "") {
      console.log(index, row);
      // identifica
      this.train = row.orderId;
      this.customerId = row.jsjid || 0;
      if(type == "change"){
        this.$router.push({
          name: "endorsedtopay",
          params: {
          train: this.train,
          customerId: '',
          orderId: row.orderId,
          merchantOrderId: this.merchantOrderIdNowArr[index],
          type: 'change',
          }
        });
      }else{
        this.$router.push({
          name: "identifica",
          params: {
            train: this.train,
            customerId: this.customerId,
            indexrow: row,
          },
        });
      }
    },
    cancelorder(index,row,type = "") {
      console.log(index, row);
      this.trainCancel = row;
      this.trainSelIndex = index;
      this.dialogType = type;
      this.cancelorderVisible = true;
    },
    // 改签弹框
    handleChange(index, row) {
      this.go = row.orderId;
      this.orderid = row.orderId;
      this.jsjid = row.id;
      console.log(row)
      this.$axios
        .getqueryTrainOrder({
          orderId: String(row.orderId),
        })
        .then((res) => {
          console.log(res);
          if (res.code == "00000") {
            this.changeMes = res.data;
            this.tableData = res.data.orderItemBOS;
          }
        });
    },
    handleselectChange(passengerList,row) {
      if(passengerList.length == 0) this.changeTable = [];
      if(passengerList.length == 0) return;
      this.$refs.multipleChangeTable.clearSelection();
      this.$refs.multipleChangeTable.toggleRowSelection(row);
      this.changeTable = [row];
    },
    btnChange() {
      console.log(this.changeMes);
      let mes = {};
      let orderItemId = [];
      let passenger = [];
      orderItemId = this.changeTable.map((item) => {
        return {
          passengersename:item.passengerName,
          passportseno:item.idNumber,
          passporttypeseid:item.idType,
          old_ticket_no:item.ticketNumber,
          piaoType:item.ticketType,
        };
      });
      this.changeTable.map((item) => {
        let obj = {
          passName: item.passengerName,
          certificateNumber: item.idNumber,
        };
        passenger.push(obj);
      });
      // let
      (mes.depart = this.changeMes.departureStation),
      (mes.arrive = this.changeMes.arrivalStation);
      (mes.orderItemId = orderItemId), 
      (mes.trainOrderId = this.changeMes.orderId);
      mes.jsjid = this.jsjid;
      // 只有一人时候可以怎么写
      mes.ticketPrice = this.changeTable[0].ticketAmount;
      console.log(mes);
      if (mes.orderItemId.length < 1) {
        this.$confirm("请先选择改签乘客", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        });
      } else {
        this.changeOrder = false;
        this.$router.push({
          name: "trainReserve",
          params: {
            mes: mes,
            type: "change",
            passenger: passenger,
            go: this.go,
          },
        });
      }
      //
    },
    // 判断改签是否能勾选
    changeOrderDisabled(row, index) {
      console.log(row, index)
        if (row.orderItemStatus  == "refundTicketSuccess" || row.orderItemStatus  == "refundTicket") {
        	return false //不可勾选
        } else {
        	return true; //可勾选
        }
      },
      // 判断退票是否能勾选
    returnOrderDisabled(row, index) {
      console.log(row, index)
        if (row.orderItemStatus  == "refundTicketSuccess" || row.orderItemStatus  == "refundTicket") {
        	return false //不可勾选
        } else {
        	return true; //可勾选
        }
      },
    //分页
    handleSizeChange(value) {
      console.log("1", value);
      localStorage.setItem("pageSize", value);
      localStorage.setItem("pageNum", 1);
      this.gettrainOrder();
      this.pageSize = value;
    },
    handleCurrentChange(value) {
      console.log("2", value);
      localStorage.setItem("pageNum", value);
      localStorage.setItem("pageSize", this.pageSize);
      this.gettrainOrder();
      // orders = res.data;
    },
    search() {
      localStorage.setItem("pageNum", 1);
      localStorage.setItem("pageSize", 10);
      this.gettrainOrder();
    },
    handleClose() {
      this.cancellog = false;
    },
    //订单列表接口
    gettrainOrder() {
      let params = {
        // userId:1,
        orderStatus:this.formLabelAlign.status
      };
      if(this.formLabelAlign.cardNumber) params["cardNumber"] = this.formLabelAlign.cardNumber
      if(this.formLabelAlign.customerName) params["customerName"] = this.formLabelAlign.customerName
      if(this.formLabelAlign.passengerName) params["passengerName"] = this.formLabelAlign.passengerName
      if(this.formLabelAlign.orderId) params["orderId"] = this.formLabelAlign.orderId
      if(this.formLabelAlign.passengerPhone) params["passengerPhone"] = this.formLabelAlign.passengerPhone
      if(this.formLabelAlign.trainNumber) params["trainNumber"] = this.formLabelAlign.trainNumber
      if(this.formLabelAlign.tripartiteOrderId) params["tripartiteOrderId"] = this.formLabelAlign.tripartiteOrderId
      if(this.formLabelAlign.ticketNumber) params["ticketNumber"] = this.formLabelAlign.ticketNumber
      if(this.formLabelAlign.orderSource) params["orderSource"] = this.formLabelAlign.orderSource
      if(this.formLabelAlign.createTime) params["createTime"] = this.formLabelAlign.createTime
      if(this.formLabelAlign.endCreateTime) params["endCreateTime"] = this.formLabelAlign.endCreateTime
      this.$axios
        .gettrainOrder(params)
        .then((res) => {
          if (res.code == "00000") {
            this.dataList = res.data.records;
            this.pageTotal = res.data.total;
            console.log(this.dataList);
            for (let i = 0; i < this.dataList.length; i++) {
              let trainOrderItemlist = this.dataList[i].orderItemBOS?this.dataList[i].orderItemBOS:[];
              let arr = [];
              let arr1 = [];
              for (let j = 0; j < trainOrderItemlist.length; j++) {
                arr.push(trainOrderItemlist[j].passengerName);
                arr1.push(
                  trainOrderItemlist[j].trainBox,
                  trainOrderItemlist[j].seatNo
                );
              }
              this.dataList[i].passengerName = arr.join(",");
              this.dataList[i].zuoweihao = arr1.join(",");
              this.btnGroupStatus(this.dataList[i],i)
            }
          }
        });
    },
    btnGroupStatus(data,parIndex){
      this.merchantOrderIdNowArr[parIndex] = ""
      // 初始按钮状态值
      data["btnGroupStatus"] = {
        detaileBtn:true,
        cancelBtn:false,
        cancleChangeBtn:false,
        goPayBtn:false,
        goPayChangeBtn:false,
        changeBtn:false,
        returnBtn:false,
      }
      // 深拷贝数据,以防止联动修改
      let orderItemS =JSON.parse(JSON.stringify(data.orderItemBOS)),changeRefundS =JSON.parse(JSON.stringify(data.changeRefundBOS));
      // 改签/退票列表有数据则合并到主订单列表
      if(changeRefundS.length){
        orderItemS.forEach((item)=>{
          if(!item.refundList) item.refundList = new Object();
          if(!item.changeList) item.changeList = new Object();
          changeRefundS.forEach((changeItem)=>{
            if(item.id === changeItem.orderItemId){
              if(changeItem.orderStatus === "changeRefundTicketSuccess" || changeItem.orderStatus === "refundTicketSuccess"){
                item.refundList=changeItem;
              }else{
                item.changeList=changeItem;
              }
            }
          })
        })
      }
      // 未支付数量，未出行数量，改签待确认数量，已改签数量，已退票数量
      var unpaidNum = 0,paidFaileNum=0,untraveledNum=0,unchangeNum=0,changeNum=0,returnNum=0;
      orderItemS.forEach((item,index)=>{
        if(item.refundList && Object.keys(item.refundList).length){
          returnNum+=1;
        } else if(item.changeList && Object.keys(item.changeList).length){
          if(item.orderItemStatus === "changeTicketSuccess" || item.orderItemStatus === "changeRefundTicketFail" || item.orderItemStatus === "refundTicketFail") changeNum+=1;
          else if(item.orderItemStatus === "changeTicket" || item.orderItemStatus === "changeTicketFail" || item.orderItemStatus === "cancelChangeTicketFail"){
            this.merchantOrderIdNowArr[parIndex] = item.changeList.merchantOrderId;
            unchangeNum+=1;
          } 
        }
        if(item.orderItemStatus === "unpaid")unpaidNum+=1;
        if(!this.merchantOrderIdNowArr[parIndex] && item.orderItemStatus === "payFail")unpaidNum+=1;
        if(this.merchantOrderIdNowArr[parIndex] && item.orderItemStatus === "payFail")unchangeNum+=1;
        if(item.orderItemStatus === "outTicketFail")paidFaileNum+=1;
        if(item.orderItemStatus === "outTicketSuccess")untraveledNum+=1;
        if(item.orderItemStatus === "changeTicketFail")untraveledNum+=1;
        if(item.orderItemStatus === "changeTicket")unchangeNum+=1;
        // if(item.orderItemStatus === "refundTicketSuccess")returnNum+=1;
        // if(item.orderItemStatus === "changeRefundTicketSuccess")returnNum+=1;
      })
      if(paidFaileNum)data.btnGroupStatus.cancelBtn = true;
      if(unpaidNum){
        data.btnGroupStatus.goPayBtn = true;
        data.btnGroupStatus.cancelBtn = true;
      }
      if(changeNum) data.btnGroupStatus.returnBtn = true;
      if(untraveledNum) data.btnGroupStatus.returnBtn = true;
      if(untraveledNum) data.btnGroupStatus.changeBtn = true;
      if(unchangeNum){
        data.btnGroupStatus.cancleChangeBtn = true;
        data.btnGroupStatus.goPayChangeBtn = true;
        data.btnGroupStatus.changeBtn = false;
      }
    },
    // 取消订单
    getcancelOrder() {
      let apiUrl = "";
      let params = {
        orderid: this.trainCancel.orderId,
      }
      if(this.dialogType === "change")apiUrl = "gettrainCancelChange"
      if(this.dialogType === "change")params["merchantOrderId"] = this.merchantOrderIdNowArr[this.trainSelIndex]
      else apiUrl = "getcancelOrder"
      this.$axios[apiUrl](params)
        .then((res) => {
          console.log(res);
          if (res.code == "00000") {
            this.gettrainOrder()((this.cancelorderVisible = false)),
              this.$message({
                message: "取消订单/改签成功",
                type: "success",
              });
          }
        });
    },
    // 订单退票弹窗
    handleDetails(index, row) {
      this.cancellog = true;
      this.train = row;
      this.getretreat(row);
    },

    // 当前行乘客信息
    handleSelectionChange(passengerList,row) {
      if(passengerList.length == 0) this.orderItemID = [];
      if(passengerList.length == 0) return;
      this.$refs.multipleReturnTable.clearSelection();
      this.$refs.multipleReturnTable.toggleRowSelection(row);
      console.log(row.merchantOrderId)
      this.orderItemID = [{
        passengername:row.passengerName,
        passportseno:row.idNumber,
        passporttypeseid:row.idType,
        ticket_no:row.ticketNumber,
        orderItemStatus:row.orderItemStatus,
        merchantOrderId:row.merchantOrderId?row.merchantOrderId:""
      }]
    },
    // 退票申请
    getretreat(row) {
      console.log(row);
      this.$axios
        .getqueryTrainOrder({
          orderId: String(row.orderId),
        })
        .then((res) => {
          if (res.code == "00000") {
            let arr = [];
            this.orderid = row.orderId;
            res.data.orderItemBOS.forEach((item)=>{
              if(item.orderItemStatus === "changeTicketSuccess" || item.orderItemStatus === "changeRefundTicketFail" || item.orderItemStatus === "refundTicketFail"){
                let changeItem = res.data.changeRefundBOS.filter(chItem =>{
                  if(chItem.orderItemId == item.id) return chItem;
                })[0]
                item["ticketNumber"] = changeItem["ticketNumber"];
                item["merchantOrderId"] = changeItem["merchantOrderId"];
              }
            })
            this.trainOrderItemList = res.data.orderItemBOS
          }
        });
    },
    closeLoading() {
      this.tableLoading.close();
    },
    showLoading() {
      this.tableLoading = this.$loading({
        text: "拼命加载数据中", //显示在加载图标下方的加载文案
        spinner: "el-icon-loading", //自定义加载图标类名
        background: "rgba(0, 0, 0, 0.4)", //遮罩层颜色
        target: document.querySelector("#table"), //loadin覆盖的dom元素节点
      });
    },
    // 退票请求
    getretreatTicket() {
      console.log(this.orderItemID);
      if (this.orderItemID.length == 0) {
        this.$message({
          message: "请至少选择一名乘客进行退票",
          type: "warning",
        });
      } else {
        this.showLoading();
        let key = "", tipStatus = []
        this.orderItemID.forEach((item,index)=>{
          let params = {
            orderid:this.orderid,
            tickets:[{
              passengername:item.passengername,
              passportseno:item.passportseno,
              passporttypeseid:item.passporttypeseid,
              ticket_no:item.ticket_no,
            }]
          }
          if(item.orderItemStatus == "changeTicketSuccess"  || item.orderItemStatus === "changeRefundTicketFail" || item.orderItemStatus === "refundTicketFail"){
            key = "postretreatTicket"
            params.tickets[0]["merchantOrderId"] = item.merchantOrderId
            console.log(params)
          
          }
          else{ 
            key = "getretreatTicket" 
          } 
          
          this.$axios[key](params).then((res)=>{
            if(res.code == "00000"){
              tipStatus.push(res.data.success)
            }
            else{
              tipStatus.push(false)
            }
            // 逻辑处理
            if(index === this.orderItemID.length-1){
              this.closeLoading();
              let errPersonArr = []
              // 筛选失败人员
              errPersonArr = tipStatus.filter((item,index)=>{
                if(!item) return this.orderItemID[index]
              })
              if(errPersonArr.length === 0){
                 this.$message({
                  message: "退票成功",
                  type: "success",
                });
              }
              if(errPersonArr.length < tipStatus.length && errPersonArr.length!=0){
                this.$message({
                  message: "部分退票成功",
                  type: "error",
                });
              }
              if(errPersonArr.length === tipStatus.length){
                this.$message({
                  message: "全部退票失败,请联系技术人员",
                  type: "error",
                });
              }
              this.cancellog = false;
              this.gettrainOrder();
            }
          })
        })
      }
    },
  },
  mounted() {
    console.log(this.formLabelAlign.createTime);
    this.search();
  },
};
</script>

<style scoped>
/deep/ .disableheadselection > .cell .el-checkbox__inner {
	display: none;
}
.header {
  width: 90%;
  height: 40px;
}

.body {
  width: 96%;
  /* margin-left: 20px; */
  padding-left: 20px;
}

.form {
  display: flex;
}

.el-form-item {
  height: 30px;
}

.elTable {
  background-color: #bbd9e6;
}

.total {
  margin: 10px;
}

.btn {
  margin-bottom: 20px;
  margin-left: 20px;
}

.table {
  padding-left: 20px;
}

.el-dialog {
  width: 65%;
}
</style>